//
//  DealInfoView.m
//  IphoneMapSdkDemo
//
//  Created by huck on 2017/5/22.
//  Copyright © 2017年 Baidu. All rights reserved.
//

#import "DealInfoView.h"
#import "AppUtils.h"
#import "HomeManager.h"
#import "MJPhoto.h"
#import "MJPhotoBrowser.h"
#import "QBImagePickerController.h"
#import "UIView+Response.h"
#import "UIViewController+Alert.h"
#import "ImageUtil.h"
#import "BMUtils.h"
#import "UIView+Response.h"

@interface DealInfoView()<UIScrollViewDelegate,QBImagePickerControllerDelegate>
@property (nonatomic,strong) NSMutableArray *imageList;
@property (nonatomic,strong) NSMutableArray *imageViewList; //固定+可变 [巡查图片] [整治图片]
@property (nonatomic,strong) WaterRecodeItemData *recordDetail; //给整改用
@property (nonatomic,strong) WaterInfoDetailData *waterDetail;  //给新增用

@property (nonatomic, strong) NSMutableArray *manageFinishUrls;  //整改完成时上传的图片集
@property (nonatomic, strong) NSMutableArray *inspectingUrls;  //巡查时上传的图片集[{@"picUrl":@"picId":}
@property (nonatomic) BOOL isAdd;
@property (nonatomic) NSInteger defaultCount;//固定图片的数量

@property (nonatomic) ScoutStatus currentStatus;

@property (nonatomic) CGFloat keyBoardHeight;
@property (nonatomic) CGFloat keyBoardDuration;
@property (nonatomic,strong) UIView *customBtnView;

@property (nonatomic) BOOL hasLocation;//是不是已经定位


@end

@implementation DealInfoView

+ (instancetype)initViewWithFrameView:(UIView *)view delegate:(id<UITextFieldDelegate>)delegate
{
    if (nil == view) {
        return nil;
    }
    DealInfoView *infoView = [[[NSBundle mainBundle] loadNibNamed:@"DealInfoView" owner:nil options:nil] firstObject];
    [infoView setFrame:CGRectMake(0, 0, view.width, view.height)];
    infoView.dealRewardField.delegate = delegate;

    [view addSubview:infoView];
    return infoView;
}

-(void)awakeFromNib
{
    [super awakeFromNib];
    [self initSubview];
}

- (void)dealloc
{}

-(void)initSubview{
    _imageList = [[NSMutableArray alloc] init];
    _imageViewList = [[NSMutableArray alloc] init];
    [_imageViewList addObject:[NSMutableArray array]];//巡查图片
    [_imageViewList addObject:[NSMutableArray array]];//整治图片
    _manageFinishUrls = [[NSMutableArray alloc] init];
    _inspectingUrls = [[NSMutableArray alloc] init];
    
    _currentStatus = ScoutStatusFinish;
    _defaultCount = 0;
    _addSuperviseView.layer.borderColor = [UIColor colorWithString:COLOR_DBD9DE].CGColor;
    _addSuperviseView.layer.borderWidth = 0.5;
    _dealRewardView.layer.borderColor = [UIColor colorWithString:COLOR_DBD9DE].CGColor;
    _dealRewardView.layer.borderWidth = 0.5;
    _dealResultViewH.constant = 0;
    _dealResultView.hidden = YES;
    _addPicView.hidden = YES;
    _addPicViewH.constant = 0;
    _dealPicView.hidden = YES;
    _dealPicViewH.constant = 0;
    [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideInput)]];
}


//整体刷新界面
-(void)updateInfo
{
    _isAdd = [AppUtils isEmpty:_recordId];
    _waterDetail= [HomeManager sharedInstance].waterDetailInfo;
    if(!_isAdd){
        _recordDetail = [HomeManager sharedInstance].waterRecordDetail;
        _manageFinishUrls = [NSMutableArray arrayWithArray:_recordDetail.manageFinishUrls];
        _inspectingUrls = [NSMutableArray arrayWithArray:_recordDetail.inspectingUrls];
    }
    _addHeadView.hidden = !_isAdd;
    _dealHeadView.hidden = _isAdd;
    if(_isAdd){
        _headViewH.constant = 60;
        _addWaterNameLabel.text = _waterDetail.waterName;
    }else{
        _dealWaterNameLable.text = _recordDetail.waterName;
        _dealRecordDayLabel.text = _recordDetail.scoutTime;
        _dealPersonLabel.text = _recordDetail.scoutName;
        NSString *superviseText = _recordDetail.supervisePropose;
        CGFloat superViewH = [AppUtils labelSizeWithString:superviseText font:[UIFont systemFontOfSize:14] maxSize:CGSizeMake(SCREEN_WIDTH-112, SCREEN_HEIGHT)].height;
        _superLabelBottom.constant += MAX(superViewH-17,0);
        _headViewH.constant = 110+MAX(superViewH-17,0);
        _dealSuperviseLabel.text = superviseText;
    }

    [self updateBadReasonView];
    [self updateDealResultView];
    [_imageViewList[0] removeAllObjects];
    [_imageViewList[1] removeAllObjects];
    //图片
    for(NSDictionary *picDict in _inspectingUrls){
        UIImageView *imageView = [[UIImageView alloc] init];
        [AppUtils setImage:imageView url:picDict[@"picUrl"]];
        imageView.accessibilityValue = picDict[@"picId"];
        [_imageViewList[0] addObject:imageView];
    }
    for(NSDictionary *picDict in _manageFinishUrls){
        UIImageView *imageView = [[UIImageView alloc] init];
        [AppUtils setImage:imageView url:picDict[@"picUrl"]];
        imageView.accessibilityValue = picDict[@"picId"];
        [_imageViewList[1] addObject:imageView];
    }
    if(!_isAdd){
        _defaultCount = _manageFinishUrls.count;
        [self initImageViews:1];
        _dealPicView.hidden = NO;
    }
    if(_isAdd || [AppUtils isNotEmptyArray:_inspectingUrls]){
        [self initImageViews:0];
        _addPicView.hidden = NO;
    }
}

//刷新一点一策的界面
-(void)updateBadReasonView
{
    NSMutableArray *badReasons = _isAdd ?_waterDetail.badReasonAnalysis : _recordDetail.badReasonAnalysis;
    NSMutableArray *badManages = _isAdd ?_waterDetail.badManageScheme : _recordDetail.badManageScheme;
    BOOL showYDYC = _isAdd ?_waterDetail.showYDYC : _recordDetail.showYDYC;
    
//    if([AppUtils isNotEmptyArray:_waterDetail.badReasonAnalysis] && showYDYC){
    if(showYDYC){
        _badReasonView.hidden = NO;
        _badTitleH.constant = 40;
        _badReasonViewH.constant = 40 +20;
        
        [AppUtils clearSubView:_reasonContainner];
        CGFloat offy = 0;
        
        for(int i=0 ;i<badReasons.count;i++){
            BadReasonItemData *item = badReasons[i];
            UIView *addView  = [AppUtils addReasonView:CGRectMake(0, offy, _reasonContainner.width, 20) title:i==0?@"原因分析:":nil reasonLabel:[[HomeManager sharedInstance] getReanalysisLabel:item.value] resonDetail:item.detail showDetail:item.showDetail target:self selector:@selector(showDetailBtnClick:)];
            if(addView != nil){
                [_reasonContainner addSubview:addView];
                offy += addView.height;
                addView.tag = i;
            }
            
        }
        for(int i=0 ;i<badManages.count;i++){
            BadReasonItemData *item = badManages[i];
            UIView *addView  = [AppUtils addReasonView:CGRectMake(0, offy, _reasonContainner.width, 20) title:i==0?@"整改方案:":nil reasonLabel:[[HomeManager sharedInstance] getMaschemeLabel:item.value] resonDetail:item.detail showDetail:item.showDetail target:self selector:@selector(showDetailBtnClick:)];
            if(addView != nil){
                [_reasonContainner addSubview:addView];
                offy += addView.height;
                addView.tag = i+100;
            }
        }
        _badReasonViewH.constant +=offy;
    }else{
        _badReasonView.hidden = YES;
        _badReasonViewH.constant = 0;
        _badTitleH.constant = 0;
    }
}

-(void)showDetailBtnClick:(UIGestureRecognizer *) recognizer
{
    NSMutableArray *badReasons = _isAdd ?_waterDetail.badReasonAnalysis : _recordDetail.badReasonAnalysis;
    NSMutableArray *badManages = _isAdd ?_waterDetail.badManageScheme : _recordDetail.badManageScheme;
    NSInteger tag = [recognizer.view superview].tag;
    if(tag>=100 && tag-100< badManages.count){
        BadReasonItemData *item = badManages[tag-100];
        item.showDetail = !item.showDetail;
        
    }else if(tag>=0 && tag<badReasons.count){
        BadReasonItemData *item = badReasons[tag];
        item.showDetail = !item.showDetail;
    }
    [self updateBadReasonView];
}

//刷新整改建议
-(void)updateDealResultView
{
    if(_isAdd){
        _dealResultView.hidden = YES;
        _dealResultViewH.constant = 0;
    }else{
        _dealResultView.hidden = NO;
        _dealResultViewH.constant = 44;
    }
}

-(void)setMyLocatoin:(CLLocationCoordinate2D)myLocatoin1
{
    _myLocatoin =myLocatoin1;
    _hasLocation = YES;
}

- (IBAction)mapGuideBtnClick:(UIButton *)sender
{
    if(_isAdd){
        if(!_hasLocation){
            [AppUtils showErrorAlert:@"定位不成功,请稍后再试"];
            return;
        }
        
        [BMUtils openMapDrivingRoute:_myLocatoin endLocation:[BMUtils getPoint:_waterDetail.mapTag] endName:_waterDetail.waterName];
    }
}

-(void)hideInput
{
    [_addSuperviseField resignFirstResponder];
    [_dealRewardField resignFirstResponder];
}

#pragma mark  ********************图片部分处理[start]************************


//刷新照片界面 上下左右顶死 //图片比例3:2,外面套view, 上间隔10 右间隔20,删除图标16*16 index 0-巡查图片 1-整治
- (void)initImageViews:(NSInteger)index
{
    NSMutableArray *resultImageViewList = _imageViewList[index];
    UIView *containerView = index==0 ? _addPicContainerView : _dealPicContainerView;
    BOOL showAdd = (_isAdd && index==0) ||(!_isAdd && index==1);
    [AppUtils clearSubView:containerView];
    UIImageView *imageView = nil;//图片比例3:2
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat marginTop = 10;//图片距离view上间隔20
    CGFloat marginRight = 20;//图片距离view上右间隔10
    CGFloat kViewWidth = (SCREEN_WIDTH - 20)/3;
    CGFloat kViewHeight = (kViewWidth-marginRight)/1.5 + marginTop;  //外套view的尺寸
    for (int i = 0; i < resultImageViewList.count; i++) {
        x = (i % 3) * kViewWidth;
        y = (i / 3) * kViewHeight;
        imageView = resultImageViewList[i];
        UIView *outView = [[UIView alloc] initWithFrame:CGRectMake(x, y, kViewWidth, kViewHeight)];
        outView.tag =index;//判断图片是那部分的
        imageView.frame = CGRectMake(0, marginTop, kViewWidth - marginRight, kViewHeight - marginTop);
        imageView.tag = i;//判断查看大图的索引
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 3;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewImage:)]];
        [outView addSubview:imageView];
        [containerView addSubview:outView];
        if(showAdd && i>=_defaultCount){
            UIButton *delButton = [[UIButton alloc] initWithFrame:CGRectMake(imageView.right-8,imageView.top-8,  16, 16)];
            delButton.tag = i;
            [delButton setImage:[UIImage imageNamed:@"deleteImage_icon"] forState:UIControlStateNormal];
            [delButton addTarget:self action:@selector(delImage:) forControlEvents:UIControlEventTouchUpInside];
            [outView addSubview:delButton];
        }
    }
    //加号图片
    if(showAdd){
        x = ((resultImageViewList.count) % 3) * kViewWidth;
        y = ((resultImageViewList.count) / 3) * kViewHeight;
        UIImageView *captureImageView = [[UIImageView alloc]initWithFrame:CGRectMake(x, y+marginTop, kViewWidth - marginRight, kViewHeight - marginTop)];
        captureImageView.userInteractionEnabled = YES;
        captureImageView.contentMode = UIViewContentModeScaleToFill;
        captureImageView.image = [UIImage imageNamed:@"add_pic_icon"];
        [captureImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(choosePicture)]];
        [containerView addSubview:captureImageView];
    }
    if(index==0){
        _addPicViewH.constant = y + kViewHeight +35+5;
    }else{
        _dealPicViewH.constant = y + kViewHeight +35+5;
    }
}

//删除缩略图
- (void)delImage:(UIButton *)sender
{
    NSInteger index = sender.tag - _defaultCount;
    if(_defaultCount<0 || _defaultCount>=_imageList.count){
        return;
    }
    NSInteger part = sender.superview.tag;
    [_imageList removeObjectAtIndex:index];
    [_imageViewList[part] removeObjectAtIndex:index];
    [self initImageViews:part];
    [self viewScrollToBottom];
}

//查看缩略图
- (void)viewImage:(UITapGestureRecognizer *)recognizer
{
    
    NSInteger part = recognizer.view.superview.tag;
    NSMutableArray *photos = [[NSMutableArray alloc] init];
    MJPhoto *photo = nil;
    UIImageView *imageView = nil;
    NSMutableArray *list = _imageViewList[part];
    for (int i = 0; i < list.count; i++) {
        imageView = [list objectAtIndex:i];
        photo = [[MJPhoto alloc] init];
        photo.image = imageView.image;
        photo.srcImageView = imageView;
        [photos addObject:photo];
    }
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.photos = photos;
    browser.currentPhotoIndex = recognizer.view.tag;
    [browser show];
}

//选择更多图片
- (void)choosePicture
{
    [self hideInput];
    __weak DealInfoView *weakself = self;
    
    [[self responderController] showActionSheetWithTitle:nil message:nil clickBlock:^(NSInteger buttonIndex) {
        if(buttonIndex == 1){
            [weakself snapImage];
        }else if(buttonIndex == 2){
            [weakself pickImage];
        }
    } cancelBottonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择",nil];
}

//拍照
- (void)snapImage
{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [AppUtils openImagePicker:[self responderController] sourceType:UIImagePickerControllerSourceTypeCamera allowsEditing:NO ratio:1];
    }];
}

//从相册里找
- (void)pickImage
{
    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.filterType = QBImagePickerControllerFilterTypePhotos;
    imagePickerController.maximumNumberOfSelection = 9;
    [[AppUtils getNavigationController] pushViewController:imagePickerController animated:YES];
}

#pragma  mark QBImagePickerControllerDelegate
/**
 从相册多选图片返回
 */
- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets
{
    [Toast loading];
    [AppUtils delay:^{
        ALAssetRepresentation *defaultRep = nil;
        UIImage *image = nil;
        for (ALAsset *asset in assets) {
            defaultRep = [asset defaultRepresentation];
            //if (defaultRep.size < IMAGE_MAX_SIZE || [StyleUtil isMagicImage:defaultRep.dimensions]) {
            //该方面使用一个CGImageRef创建UIImage，在创建时还可以指定方法倍数以及旋转方向。当scale设置为1的时候，新创建的图像将和原图像尺寸一摸一样，而orientaion则可以指定新的图像的绘制方向
            image = [UIImage imageWithCGImage:defaultRep.fullResolutionImage scale:defaultRep.scale orientation:(UIImageOrientation)defaultRep.orientation];
            //} else {
            // image = [UIImage imageWithCGImage:defaultRep.fullScreenImage];//这里会缩小成1334*1334的最大范围,所以500*5000的会缩小成133*1334,无形中缩小了
            //            }
            [self addPhoto:image thumbnail:[UIImage imageWithCGImage:asset.thumbnail]];
        }
        [self initImageViews:_isAdd ? 0:1];
        [Toast loaded];
        [[AppUtils getNavigationController] popToViewController:[self responderController] animated:YES];
        [self viewScrollToBottom];
    }];
}

//拍照图片返回
- (void)didFinishCropperImage:(UIImage *)image
{
    [self addPhoto:[AppUtils fixImageOrientation:image] thumbnail:nil];
    [self initImageViews:_isAdd ? 0:1];
    [self viewScrollToBottom];
}

- (void)addPhoto:(UIImage *)image thumbnail:(UIImage *)thumbnail
{
    if (thumbnail == nil) {
        thumbnail = image;
    }
    [_imageList addObject:image];
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = image;
    NSInteger part = _isAdd ? 0:1;
    [_imageViewList[part] addObject:imageView];
}

-(void)viewScrollToBottom
{
//    [_scrollView setContentOffset:CGPointMake(0,  _scrollView.contentSize.height - _scrollView.height) animated:YES];
}

#pragma mark  ********************图片部分处理[end]************************


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self hideInput];
}

- (IBAction)cancelBtnClick:(UIButton *)sender
{
    [[AppUtils getNavigationController] popViewControllerAnimated:YES];
}

- (IBAction)submitBtnClick:(UIButton *)sender
{
    NSString *superText = _isAdd ? [AppUtils trim: _addSuperviseField.text] :[AppUtils trim: _dealRewardField.text];
    NSString *fileFlag = _isAdd ? @"inspecting" :@"manageFinish";
    NSString *taskId = _isAdd ? _waterId :_recordId;
//    if(_imageList.count ==0){
//        [Toast makeText:@"您必须添加一张图片"];
//        return;
//    }
    NSLog(@"%@===图片数%zi====%@",superText,_imageList.count, taskId);
    NSMutableArray *resultImgs = [NSMutableArray array];
    [Toast loading];
    for(UIImage *image in _imageList){
        //压缩图片
        UIImage *cutImage = nil;
        if(image.size.width>image.size.height){
            cutImage = [ImageUtil compress:image newWidth:540];
        }else{
            cutImage = [ImageUtil compress:image newHeight:960];
        }
        cutImage = [AppUtils compressImageQualityToImage:cutImage];
        [resultImgs addObject:cutImage];
    }
    
    [[HomeManager sharedInstance] requestUploadImages:resultImgs flag:fileFlag completion:^(BOOL success, NSArray *fileArr) {
        if(success){
            NSLog(@"/n%@/n",fileArr);
            NSArray *fileIds = fileIds = [AppUtils joinArrayDict:fileArr WithKey:@"fileId"];
            [[HomeManager sharedInstance] requestAddRecoreOrDeal:taskId type:_isAdd text:superText fieldIds:fileIds completion:^(BOOL success) {
                [Toast loaded];
                if(success){
                    [[AppUtils getNavigationController] popViewControllerAnimated:YES];
                }
            }];
        }else{
            [Toast loaded];
        }
    }];
}

@end
